package middleware

import (
	"copper-cloud/pkg/logging"
	"github.com/gin-gonic/gin"
	"github.com/segmentio/ksuid"
	"time"
)

// Ginzap http请求定制化日志
func Ginzap() gin.HandlerFunc {
	return func(c *gin.Context) {
		TraceID := ksuid.New().String()
		c.Request.Header.Set("X-Request-ID", TraceID)
		start := time.Now()
		path := c.Request.URL.Path
		logging.ZapLogger.Infow("Inbound","path", path,
			"method", c.Request.Method,
			"ip", c.ClientIP(), "user-agent",
			c.Request.UserAgent(),
			"traceId", TraceID)
		c.Next()

		end := time.Now()
		latency := end.Sub(start)

		if len(c.Errors) > 0 {
			// Append error field if this is an erroneous request.
			for _, e := range c.Errors.Errors() {
				logging.ZapLogger.Error(e)
			}
		} else {
			// 打印接口处理后的信息
			logging.ZapLogger.Infow("Outbound",
				"path", path,
				"method", c.Request.Method,
				"status", c.Writer.Status(),
				"latency", latency,
				"traceId", TraceID,
			)
		}
	}
}